import device from "../device";
import Vue from 'vue'

// 加载微信
function loadJs (url, callback) {
    let script = document.createElement('script')
    script.type = 'text/javascript'
    if (typeof callback === 'function') {
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState === 'loaded' || script.readyState === 'complete') {
                    script.onreadystatechange = null
                    callback()
                }
            }
        } else {
            script.onload = callback
            script.onerror = callback
        }
    }
    script.src = url
    document.body.appendChild(script)
}

function loadWx (callback) {
    if (!device.isWechat) return;
    const register_weChat = typeof callback === 'function' ? callback : function () {

    };


    const jsapi = [
        '//res.wx.qq.com/open/js/jweixin-1.4.0.js',
        '//res2.wx.qq.com/open/js/jweixin-1.4.0.js'
    ]
    let i = 0

    function fun () {
        const url = jsapi[i]
        i++
        console.log(url, '加载')
        if (!url) return
        if (!window.jWeixin) loadJs(url, function (response, status) {
            if (window.jWeixin) register_weChat()
            else fun()
        })
    }

    fun()
}

class Basic {
    constructor () {
        let that = this;
        this.currentRegisterPage = '';
        //#ifdef H5
        // this.wx_jssbk = require('../../js_sdk/jsweixin/1.4.1');
        // this.miniProgram = this.wx_jssbk.miniProgram;
        //#endif
        this.jsApiList = [
            'checkJsApi',
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onVoiceRecordEnd',
            'playVoice',
            'onVoicePlayEnd',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard'
        ]

        Vue.mixin({
            onLoad: function () {
                that.resetUrl()
            }
        })
    }

    load () {
        let that = this;
        if (that.wx_jssbk) return Promise.resolve();
        return new Promise(resolve => {
            loadWx(function () {
                const wx = window.jWeixin;
                that.wx_jssbk = wx;
                that.miniProgram = wx.miniProgram;
                resolve()
            });
        })
    }

    resetUrl () {
        this.currentRegisterPage = '';
    }

    async init () {
        let vm = this;
        await this.load();
        const jsApiList = vm.jsApiList;
        return new Promise(async (resolve, reject) => {
            //#ifdef H5
            const url = window.location.href.split('#')[0];
            const wx_jssbk = vm.wx_jssbk;
            vm.miniProgram && vm.miniProgram.getEnv((res) => device.isMiniWechat = res.miniprogram);
            window.__wxjs__register = true;
            //
            if (!device.isWechat || process.env.NODE_ENV === 'development') {
                window.__wxjs__register = false;
                console.log('不是微信环境或发布环境');
                return reject('不是微信环境或发布环境');
            }
            if (url === vm.currentRegisterPage) return resolve();
            const result = await Vue.$ajax.WeChat.getWxSignature(url);
            if (result && result.code === 0) {
                const data = {...result.data};
                wx_jssbk.config({
                    debug: false,
                    appId: data.appId,
                    timestamp: data.timestamp,
                    nonceStr: data.nonceStr,
                    signature: data.signature,
                    jsApiList
                });
            }
            wx_jssbk.error(function (res) {
                // config信息验证失败会执行error函数，
                // 如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，
                // 也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                console.log('微信注册失败', ...res);
                window.__wxjs__register = false;
                vm.currentRegisterPage = '';
                reject();
            });
            wx_jssbk.ready(function () {
                console.log(arguments);
                setTimeout(function () {
                    if (window.__wxjs__register === true) {
                        console.log('微信注册成功');
                        vm.currentRegisterPage = url;
                        resolve();
                    }
                }, 100)
            });

            //#endif
            // #ifndef H5
            reject()
            // #endif
        });
    }

    async setShareData () {
        await this.init();
        const wx_jssbk = this.wx_jssbk;
        let wxShare = null;
        if (!wx_jssbk) return Promise.reject();
        if (Vue.$global_util.jude.isEmptyObject(data && true)) {
            wxShare = null
        }
        // 分享给朋友(即将废弃)
        wx_jssbk.onMenuShareAppMessage && wx_jssbk.onMenuShareAppMessage(wxShare);
        // 分享到朋友圈(即将废弃)
        wx_jssbk.onMenuShareTimeline && wx_jssbk.onMenuShareTimeline(wxShare);
        // 分享到QQ(即将废弃)
        wx_jssbk.onMenuShareQQ && wx_jssbk.onMenuShareQQ(wxShare);
        // 分享到腾讯微博(即将废弃)
        wx_jssbk.onMenuShareWeibo && wx_jssbk.onMenuShareWeibo(wxShare);
        // 分享到QQ空间(即将废弃)
        wx_jssbk.onMenuShareQZone && wx_jssbk.onMenuShareQZone(wxShare);
        // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）
        wx_jssbk.updateAppMessageShareData && wx_jssbk.updateAppMessageShareData(wxShare, function (res) {
            console.log(res, '自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）');
            wxShare && typeof wxShare.success === "function" && wxShare.success()
        });
        // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
        wx_jssbk.updateTimelineShareData && wx_jssbk.updateTimelineShareData(wxShare, function (res) {
            console.log(res, '自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）');
            wxShare && typeof wxShare.success === "function" && wxShare.success()
        });
        return Promise.resolve()
    }
}


class WeChatMethodS extends Basic {
    constructor () {
        super();
    }

    async getLocation ({type = 'gcj02'}) {
        await this.init();
        const wx_jssbk = this.wx_jssbk;
        wx_jssbk.getLocation({
            type,
            success (res) {
                console.log(res, '+++++++++++++++++++++');
            },
            fail (res) {
                console.log(res, '+++++++++++++++++++++');
            }
        })
    }

    scanQRCode ({scanType = ["qrCode", "barCode"]} = {}) {
        let vm = this;
        return new Promise(async resolve => {
            //#ifdef H5
            await vm.init();
            const wx_jssbk = this.wx_jssbk;
            wx_jssbk.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: scanType, // 可以指定扫二维码还是一维码，默认二者都有,
                success (res) {
                    const result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    resolve({...res, result})
                },
                fail: resolve,
                complete (res) {
                    // const result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    // resolve({...res, result})
                }
            });
            //#endif
            //#ifndef H5
            uni.scanCode({
                onlyFromCamera: false,
                scanType: scanType, // 可以指定扫二维码还是一维码，默认二者都有,
                success: resolve,
                fail: resolve
            })
            //#endif
        })
    }
}

export default new WeChatMethodS();
